package com.bysc.cmsservice.controller;


import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.RedisUtil;
import com.bysc.cmsservice.utils.MinioUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import static com.bysc.commonutils.constant.RedisConstant.FILE_URL_RESOURCES;

/**
 * minio上传流程
 * <p>
 * 1.检查数据库中是否存在上传文件
 * <p>
 * 2.根据文件信息初始化，获取分片预签名url地址，前端根据url地址上传文件
 * <p>
 * 3.上传完成后，将分片上传的文件进行合并
 * <p>
 * 4.保存文件信息到数据库
 */
@RestController
@Slf4j
@Api(tags = "文件管理")
@RequestMapping("minioservice/minio-upload")
public class FileMinioController {

    //    @Resource
//    private UploadService uploadService;
    @Resource
    private RedisUtil redisUtil;
//    @Resource
//    private MinioUtils minioUtils;
//    @Autowired
//    private FilesService filesService;
    @Autowired
    private MinioUtils minioUtils;
    /**
     * @description 获取上传文件
     * @param fileMD5 文件md5
     * @return {@link Results }
     */
/*    @ApiOperation(value = "根据md5获取上传文件")
    @GetMapping("/getUploadingFile/{fileMD5}")
    public Results getUploadingFile(@PathVariable String fileMD5) {
        if (StringUtils.isBlank(fileMD5)) {
            return Results.error();
        }
        FileUploadInfo fileUploadInfo = (FileUploadInfo) redisUtil.get(fileMD5);
        if (fileUploadInfo != null) {
            // 查询上传后的分片数据
            fileUploadInfo.setChunkUploadedList(minioUtils.getChunkByFileMD5(fileUploadInfo.getFileName(), fileUploadInfo.getUploadId(), fileUploadInfo.getFileType()));
            return Results.ok().data("fileUploadInfo",fileUploadInfo);
        }
        return Results.error();
    }*/

    /**
     * 校验文件是否存在
     *
     * @param md5 String
     * @return ResponseResult<Object>
     */
/*    @ApiOperation(value = "检验文件是否存在")
    @GetMapping("/multipart/check")
    public Results checkFileUploadedByMd5(@RequestParam("md5") String md5) {
        log.info("REST: 通过查询 <{}> 文件是否存在、是否进行断点续传", md5);
        if (StringUtils.isEmpty(md5)) {
            log.error("查询文件是否存在、入参无效");
            return Results.error().message(RespEnum.ACCESS_PARAMETER_INVALID.getMessage());
        }
        return uploadService.getByFileMD5(md5);
    }*/

    /**
     * 分片初始化
     *
     * @param fileUploadInfo 文件信息
     * @return ResponseResult<Object>
     */
/*    @ApiOperation(value = "上传初始化，返回一个或多个url上传地址")
    @PostMapping("/multipart/init")
    public Results initMultiPartUpload(@RequestBody FileUploadInfo fileUploadInfo) {
        log.info("REST: 通过 <{}> 初始化上传任务", fileUploadInfo);
        return Results.ok().data(uploadService.initMultiPartUpload(fileUploadInfo));
    }*/

    /**
     * 完成上传
     *
     * @param fileUploadInfo 文件信息
     * @return ResponseResult<Object>
     */
/*    @ApiOperation(value = "完成上传，合并分片")
    @PostMapping("/multipart/merge")
    public Results completeMultiPartUpload(@RequestBody FileUploadInfo fileUploadInfo) {
        log.info("REST: 通过 {} 合并上传任务", fileUploadInfo);
        //合并文件
        String url = uploadService.mergeMultipartUpload(fileUploadInfo);
        //获取上传文件地址
        if (StringUtils.isNotBlank(url)) {
            return Results.ok().data("url",url);
        }
        return Results.error();
    }*/
/*    @ApiOperation(value = "普通上传-多文件")
    @PostMapping("/multipart/uploadScreenshot")
    public Results uploaduploadScreenshot(@RequestPart("photos") MultipartFile[] photos,
                                    @RequestParam("buckName") String buckName) {
        log.info("REST: 上传文件信息 <{}> ", photos);

        for (MultipartFile photo : photos) {
            if (!photo.isEmpty()) {
                uploadService.upload(photo, buckName);
            }
        }
        return Results.ok();
    }*/
/*
    @ApiOperation(value = "创建一个存储桶(文件夹)")
    @RequestMapping("/createBucket")
    public void createBucket(@RequestParam("bucketName") String bucketName) {
        String bucket = minioUtils.createBucket(bucketName);
    }
    @ApiOperation(value = "根据桶名称和文件名删除文件")
    @DeleteMapping ("deleteFile")
    public Results deleteFile(@RequestParam("bucketName") String bucketName,@RequestParam("objectName") String objectName) {
        try {
            minioUtils.deleteObject(bucketName,objectName);
            QueryWrapper<Files> queryWrapper = new QueryWrapper<Files>().eq("fileName", objectName);
            filesService.remove(queryWrapper);
            return Results.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaiYunException(20001, "error");
        }
    }*/

    // 文件上传接口
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public Results uploadFile(@ApiParam(name = "bucketName", value = "桶名（avatar-头像，banner-轮播图，comment-评论图，dept-部门图，student-协会成员图，study-学习资料，activity-公告，feedback-反馈）", required = true) @RequestParam("bucketName") String bucketName, @RequestParam("file") MultipartFile file) {
        try {
            String url = minioUtils.upload(file, bucketName);
            if (url!=null) {
                redisUtil.sSet(FILE_URL_RESOURCES,url);
            }
            return Results.ok().data("url",url).message(MessageConstant.UPLOAD_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR,MessageConstant.UPLOAD_FAIL);
        }
    }

}